<?php
// +----------------------------------------------------------------------
// | RXThinkCMF框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2020 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: 牧羊人 <1175401194@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\service;

use app\admin\model\OfCompany;
use app\common\service\BaseService;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\facade\Db;

/**
 * 客户管理-服务类
 * @author 牧羊人
 * @since: 2021/12/21
 * Class OfCompanyService
 * @package app\admin\service
 */
class OfCompanyService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new OfCompany();
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2021/12/21
     * @author 牧羊人
     */
    public function getList()
    {
        $param = request()->param();

        // 查询条件
        $map = [];

        $admin_id = session("adminId");

        // 公司名称
        $name = isset($param['name']) ? trim($param['name']) : '';
        if ($name) {
            $map[] = ['name', 'like', "%{$name}%"];
        }

        $role_id  = Db::name("admin")->where('id', '=', $admin_id)->value("role_ids");
        $arr_role = explode(",", $role_id);
        if (count($arr_role) == 1) {
            if ($role_id == 3) {
                $map[] = ['service_id', 'like', "%$admin_id%"];
            } else if ($role_id == 4) {
                $map[] = ['agent_id', 'like', "%$admin_id%"];
            } else if ($role_id == 5) {
                $map[] = ['peer_id', '=', $admin_id];
            }
        } else {
            $map[] = ['service_id', 'like', "%$admin_id%"];
        }

        $list = parent::getList($map);
        if (!empty($list['data'])) {
            foreach ($list['data'] as $key => &$value) {
                $value['peer_str'] = '';
                if (!empty($value["peer_id"])) {
                    $value['peer_str'] = Db::name("admin")->where("id", $value['peer_id'])->value("username");
                }
                $value['agent_str'] = '';
                if (!empty($value['agent_id'])) {
                    $value['agent_str'] = Db::name("admin")->where("id", $value['agent_id'])->value("username");
                }
                $value['service_str'] = '';
                if (!empty($value["service_id"])) {
                    $value['service_str'] = Db::name("admin")->where("id", $value['service_id'])->value("username");
                }
            }
        }
        return $list; // TODO: Change the autogenerated stub
    }

    /**
     * 第一行是标头
     * 第二行是数据
     */
    public function readFile($file, $line)
    {
        // 判断文件是什么格式
        $type = pathinfo($file);
        $type = strtolower($type["extension"]);
        if ($type == 'xlsx') {
            $type = 'Xlsx';
        } else {
            $type = 'Xls';
        }

        // 判断使用哪种格式
        $objReader = IOFactory::createReader($type);

        $objPHPExcel = $objReader->load($file);
        $sheet       = $objPHPExcel->getSheet(0);

        // 取得总行数
        $highestRow = $sheet->getHighestRow();
        // 取得总列数
        $highestColumn = $sheet->getHighestColumn();
        ++$highestColumn;
        //循环读取excel文件,读取一条,插入一条
        $data = array();
        //从第二行开始读取数据
        for ($j = $line; $j <= $highestRow; $j++) {
            //从A列读取数据
            for ($k = 'A'; $k != $highestColumn; $k++) {
                // 读取单元格
                $data[$j][] = trim((string) $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue());
            }
        }
        return $data;
    }

    /**
     * 将excel导入时 xx-xx-xx 变成数字的解决
     */
    public function changDate($date)
    {
        if($date){
            if (is_numeric($date)) {
                $t1   = intval(($date - 25569) * 3600 * 24);
                $date = gmdate('Y-m-d', $t1);
            } else {
                $date = strtotime($date);
                $date = date('Y-m-d');
            }
        }
        
        return $date;
    }

    /**
     * $data 字段名称
     *
     */
    public function checkDuplicate($data, $save_data)
    {
        $key_arr = [];
        $v_arr   = [];
        foreach ($data as $key => $value) {
            foreach ($value as $k => $v) {
                $key_arr[] = $k;
                $v_arr[]   = $v;
            }
        }
        $length = 0;
        foreach ($save_data as $key => $value) {
            foreach ($key_arr as $k => $v) {
                if ($value[$v] == $v_arr[$k]) {
                    $length++;
                }
            }
        }
        //相等即为多条件也重合了
        if ($length == count($data)) {
            return true;
        }
        return false;
    }

    // //导出功能
    // public function exportExcel($param)
    // {   
    //     ini_set('max_execution_time', '0');
    //     // 查询要导出的数据
    //     $map = [
    //         ['mark','=',1],
    //     ];
    //     if($param['name']){
    //         $map[] = ['name','like','%'.$param['name'].'%'];
    //     }
    //     $data = $this->model->where($map)->order('id desc')->select();
    //     // 实例化
    //     $spreadsheet = new Spreadsheet();
    //     // 获取活动单元格

    //     $sheet = $spreadsheet->getActiveSheet();

    //     // 获取单元格
    //     $cellA = $sheet->getCell('A1');
    //     // 设置单元格的值
    //     $cellA->setValue('公司名称');
    //     // 设置 A 列 列宽
    //     $sheet->getColumnDimension('A')->setWidth(50);
    //     // 设置第一行 行高
    //     $sheet->getRowDimension(1)->setRowHeight(20);

    //     $cellB = $sheet->getCell('B1');
    //     $cellB->setValue('同行公司');
    //     $sheet->getColumnDimension('B')->setWidth(50);

    //     $cellC = $sheet->getCell('C1');
    //     $cellC->setValue('业务员');
    //     $sheet->getColumnDimension('C')->setWidth(15);

    //     $cellD = $sheet->getCell('D1');
    //     $cellD->setValue('代理人');
    //     $sheet->getColumnDimension('D')->setWidth(15);

    //     $cellE = $sheet->getCell('E1');
    //     $cellE->setValue('联系人');
    //     $sheet->getColumnDimension('E')->setWidth(15);

    //     $cellE = $sheet->getCell('F1');
    //     $cellE->setValue('电话');
    //     $sheet->getColumnDimension('F')->setWidth(20);

    //     $cellF = $sheet->getCell('G1');
    //     $cellF->setValue('地址');
    //     $sheet->getColumnDimension('G')->setWidth(50);

    //     $cellG = $sheet->getCell('H1');
    //     $cellG->setValue('总委编号');
    //     $sheet->getColumnDimension('H')->setWidth(15);

    //     $cellH = $sheet->getCell('I1');
    //     $cellH->setValue('费减备案年份');
    //     $sheet->getColumnDimension('I')->setWidth(15);


    //     // 设置样式 标题
    //     $styleArray = [
    //         'alignment' => [
    //             'horizontal' => 'center', //水平居中
    //             'vertical'   => 'center', //垂直居中
    //         ],
    //         'font'      => [
    //             'name' => '黑体',
    //             'bold' => false,
    //             'size' => 10,
    //         ],
    //     ];
    //     // 设置样式 正文
    //     $styleArrayBody = [
    //         'alignment' => [
    //             'horizontal' => 'center', //水平居中
    //             'vertical'   => 'center', //垂直居中
    //         ],
    //         'font'      => [
    //             'name' => '宋体',
    //             'bold' => false,
    //             'size' => 10,
    //         ],
    //     ];
    //     // 应用样式
    //     $sheet->getStyle('A1')->applyFromArray($styleArray);
    //     $sheet->getStyle('B1')->applyFromArray($styleArray);
    //     $sheet->getStyle('C1')->applyFromArray($styleArray);
    //     $sheet->getStyle('D1')->applyFromArray($styleArray);
    //     $sheet->getStyle('E1')->applyFromArray($styleArray);
    //     $sheet->getStyle('F1')->applyFromArray($styleArray);
    //     $sheet->getStyle('G1')->applyFromArray($styleArray);
    //     $sheet->getStyle('H1')->applyFromArray($styleArray);
    //     $sheet->getStyle('I1')->applyFromArray($styleArray);

    //     // 从 A2 开始填充数据
    //     foreach ($data as $k => $v) {
    //         //同行公司 名称获取
    //         $tong_name = Db::name("admin")->where("id", $v['peer_id'])->value('realname');
    //         //业务员
    //         $ye_name = Db::name("admin")->where("id", $v['service_id'])->value('realname');
    //         //代理
    //         $agent_name = Db::name("admin")->where("id", $v['agent_id'])->value('realname');

    //         $n = $k + 2;
    //         // 获取单元格
    //         $cellA = $sheet->getCell('A' . $n);
    //         // 设置单元格的值
    //         $cellA->setValue($v['name']);

    //         $cellB = $sheet->getCell('B' . $n);
    //         $cellB->setValue($tong_name);

    //         $cellC = $sheet->getCell('C' . $n);
    //         $cellC->setValue($ye_name);

    //         $cellD = $sheet->getCell('D' . $n);
    //         $cellD->setValue($agent_name);

    //         $cellD = $sheet->getCell('E' . $n);
    //         $cellD->setValue($v['contacts_name']);

    //         $cellD = $sheet->getCell('F' . $n);
    //         $cellD->setValue($v['phone']);

    //         $cellE = $sheet->getCell('G' . $n);
    //         $cellE->setValue($v['address']);

    //         $cellF = $sheet->getCell('H' . $n);
    //         $cellF->setValue($v['general_number']);

    //         $cellG = $sheet->getCell('I' . $n);
    //         $cellG->setValue($v['fee_year']);
    //     }

    //     $file_name = '客户('.date("Y-m-d H:i:s",time()).').xlsx';
    //     // 实例化导出类
    //     header('Content-Type:application/vnd.ms-excel');
    //     header('Content-Disposition:attachment;filename=' . $file_name);
    //     header('Cache-Control:max-age=0');

    //     $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
    //     $writer->save('php://output');
    // }

     //导出功能
    public function exportExcel($head,$new_arr,$fileName)
    {   
        $cell_data  = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
        // 实例化
        $spreadsheet = new Spreadsheet();
        // 获取活动单元格

        $sheet = $spreadsheet->getActiveSheet();
        // 设置第一行 行高
        $sheet->getRowDimension(1)->setRowHeight(20);


        // 设置样式 标题
        $styleArray = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical'   => 'center', //垂直居中
            ],
            'font'      => [
                'name' => '黑体',
                'bold' => false,
                'size' => 10,
            ],
        ];
        // 设置样式 正文
        $styleArrayBody = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical'   => 'center', //垂直居中
            ],
            'font'      => [
                'name' => '宋体',
                'bold' => false,
                'size' => 10,
            ],
        ];

        foreach ($head as $key => $value) {
            $cellA = $sheet->getCell($cell_data[$key].'1');
            $cellA->setValue($value['title']);
            $sheet->getColumnDimension($cell_data[$key])->setWidth($value['width']);

            // 应用样式
            $sheet->getStyle($cell_data[$key].'1')->applyFromArray($styleArray);

        }

        // 从 A2 开始填充数据
        foreach ($new_arr as $key => $value) {
            $n = $key + 2;

            foreach ($value as $k => $v) {
                // 获取单元格
                $cellA = $sheet->getCell($cell_data[$k] . $n);
                // 设置单元格的值
                $cellA->setValue($v);
            }
        }

        $file_name = $fileName.'.xlsx';
        // 实例化导出类
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename=' . $file_name);
        header('Cache-Control:max-age=0');

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
}
